package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocal;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author gxm
 * @since 2023-12-18
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult findList(WmNewsPageDto dto) {

        //设置分页条件
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        //设置业务条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper();
        wrapper
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())//关键字
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())//频道
                .eq(WmNews::getUserId, UserThreadLocal.get().getUserId())//用户id
                .orderByDesc(WmNews::getPublishTime);//排序
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) { //发布时间
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
            wrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }

        //执行查询
        this.page(page, wrapper);

        //返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult submit(WmNewsDto dto) {

        //1. 判断id是否有值，如果有值代表修改
        if (dto.getId() != null) {
            //删除已关联的素材关系 DELETE  FROM wm_news_material WHERE news_id=？
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId, dto.getId());
            wmNewsMaterialService.remove(queryWrapper);
        }

        //2. 赋值
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews); //从dto中拷贝属性
        wmNews.setUserId(UserThreadLocal.get().getUserId());
        wmNews.setCreatedTime(new Date());
        List<ImageDto> coverImages = dto.getImages();
        wmNews.setImages(JSON.toJSONString(coverImages));//封面图片

        //从文章内容中获取图片
        List<ImageDto> contentImages = getImagesFromContent(dto.getContent());
        //如果是自动选图
        if (dto.getType() == -1) {
            int size = contentImages.size();
            //wmNews.setType(); //文章封面类型  0 无图 1 单图 3 多图 -1 自动 TODO
            if (size == 0) {
                wmNews.setType(0);
            } else if (size == 1 || size == 2) {
                wmNews.setType(1);
                coverImages = contentImages.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(coverImages));

            } else {
                wmNews.setType(3);
                coverImages = contentImages.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(coverImages));
            }
        }
        this.saveOrUpdate(wmNews); //新增或修改
        if (dto.getStatus() == 1) {
            saveRelation(contentImages, wmNews.getId(), 0); //保存文章内容图片
            saveRelation(coverImages, wmNews.getId(), 1); //保存文章封面图片

            //完成审核
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        WmNews wmNews = this.getById(dto.getId());
        Integer status = wmNews.getStatus();
        //是否为发布或人工审核通过状态
        if (status != 4 && status != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NOT_DOWN_OR_UP);
        }
        //设置状态
        Integer enable = dto.getEnable(); //1:true   0:false
        wmNews.setEnable(enable == 1);
        this.updateById(wmNews);

        //投递消息到rabbitmq
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",enable==0);
        //交换机名称  路由名称  值
        rabbitTemplate.convertAndSend("article.topic", "article.up_or_down", map);

        return ResponseResult.okResult();
    }


    //保存文章图片
    private void saveRelation(List<ImageDto> contentImages, Integer newsId, int type) { //0 内容图片  1 封面图片
        int i = 0;
        for (ImageDto contentImage : contentImages) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(contentImage.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(i);
            wmNewsMaterialService.save(wmNewsMaterial);
            i++;
        }
    }

    //从文章内容中获取图片
    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> imageDtoList = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (StringUtils.equals(contentDto.getType(), "image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }

        return imageDtoList;
    }
}
